package com.abing.core.utils;

import com.abing.core.utils.xml.ResponseCardQueryBodyBO;
import com.abing.core.utils.xml.ResponseDocumentBO;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class JaxbUtil {//工具类

    /**
     * java对象转换为xml文件
     * @param obj  xml文件路径
     * @param load    java对象.Class
     * @return    xml文件的String
     * @throws JAXBException    
     */
    public static String beanToXml(Object obj, Class<?> load) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(load);
        Marshaller marshaller = context.createMarshaller();
        // 指定是否使用换行和缩排对已编组 XML 数据进行格式化的属性名称。
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
        marshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        return writer.toString();
    }

    /**
     * xml文件配置转换为对象
     * @param xmlPath  xml文件路径
     * @param load    java对象.Class
     * @return    java对象
     * @throws JAXBException    
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static <T> T xmlToBean(String xmlPath, Class<T> load) throws JAXBException, IOException {
        JAXBContext context = JAXBContext.newInstance(load);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return (T) unmarshaller.unmarshal(new StringReader(xmlPath));
    }
    
    /** 
     * JavaBean转换成xml 
     * 默认编码UTF-8 
     * @param obj 
     * @param writer 
     * @return  
     */
    public static String convertToXml(Object obj) {
        //       return convertToXml(obj, "UTF-8");  
        return convertToXml(obj, "UTF-8");
    }

    /** 
     * JavaBean转换成xml 
     * @param obj 
     * @param encoding  
     * @return  
     */
    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    
    /** 
     * JavaBean转换成xml去除xml声明部分 
     * @param obj 
     * @param encoding  
     * @return  
     */
    public static String convertToXmlIgnoreXmlHead(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    
    
    

    /** 
     * xml转换成JavaBean 
     * @param xml 
     * @param c 
     * @return 
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return t;
    }

    public static void main(String[] args) {

        String outXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><document><response><head><version>3.7.0</version><appid>2016012900930739</appid><function>alipay.medical.card.query</function><respTime>20180330122158</respTime><respTimeZone>UTC+8</respTimeZone><reqMsgId>78bc03b3-8c81-4ae7-a1c5-a02cfd0803a2</reqMsgId></head><body><resultInfo><resultStatus>S</resultStatus><resultCode>SUCCESS</resultCode><resultMsg>业务成功</resultMsg></resultInfo><medical_card_id>6049735182</medical_card_id><medical_card_no>B6C989166</medical_card_no><medical_card_validate_date>2038-03-30</medical_card_validate_date><medical_card_status>active</medical_card_status><medical_card_type>finance</medical_card_type><bank_card_no>6214677200012756150</bank_card_no><out_real_name>林海毅</out_real_name><out_user_card_type>01</out_user_card_type><out_user_card_no>450502198805230162</out_user_card_no><social_card_no>450502198805230162</social_card_no><extend_params>{\"card_query\":{\"dnh\":\"640750316\"}}</extend_params></body></response><signature>LuhjShqmZjFUHQ7SVxqELZnyUHB4EU/nWO4Or8RUJBbmSfsS+ChONxpGNCXYjGvd5Jfn8+t3ugqqKYPCGsRy3UDec63a2PllSKJCA1sOYSGfKDz0W38mSIgL/jWNXd4ryiijzQi4BQbTlHIoms6X5AhXeL30QW6dLpdvZlPHYWrjtS97n/991FJZDcb7df/UYYjZaicL+LhjUpG1WkN93PJc3RLzsHXF2u3OMAirTR7bhYx2L9bnY2VxnWiMPBcxBVB26r03bD5I5iqL8iLqmVcFqOQHt7iozUGywe71eBEV8dlgzDCswv3unCiywU8Ndvw/VOKdZXQ6OERbpGDCqA==</signature></document>";
        ResponseDocumentBO<ResponseCardQueryBodyBO> outDocumentXml = JaxbUtil.converyToJavaBean(outXml, ResponseDocumentBO.class);
        System.out.println(outDocumentXml.toString());
    }
}